package com.yenlien.traceyun.business.config;

import java.lang.reflect.Field;
import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.common.bean.UserInfo;
import com.yenlien.traceyun.common.crypt.TokenUtil;
import com.yenlien.traceyun.common.utils.LoggerUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 持久化之前
 *
 * @author master yi
 */
public class SaveListener {


    @PrePersist
//	@PreUpdate
    public void preUpdate(Object source) {
        try {
            UserInfo userInfo = UserAuthUtil.getLoginUser();
            Field companyId = source.getClass().getSuperclass().getDeclaredField("companyId");
            Field userId = source.getClass().getSuperclass().getDeclaredField("userId");
            Field id = source.getClass().getSuperclass().getDeclaredField("id");
            companyId.setAccessible(true);
            userId.setAccessible(true);
            id.setAccessible(true);
            if (userInfo != null) {
                if (StringUtils.isEmpty(companyId.get(source))) {
                    companyId.set(source, userInfo.getCompanyId());
                }
                if (StringUtils.isEmpty(userId.get(source))) {
                    userId.set(source, userInfo.getId());
                }
            }
            Object idObj = id.get(source);
            if (StringUtils.isEmpty(idObj)) {
                Field createtime = source.getClass().getSuperclass().getDeclaredField("createtime");
                createtime.setAccessible(true);
                if (StringUtils.isEmpty(createtime.get(source))) {
                    createtime.set(source, new Date());
                }
            }
        } catch (Exception e) {
            LoggerUtil.getLogger().error("preupate is error:{}", e.getMessage());
        }
    }

    private JSONObject get() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            String body = TokenUtil.getBody(token);
            return JSONObject.parseObject(body);
        } else {
            return (JSONObject) request.getSession().getAttribute("userInfo");
        }
    }


}
